import request from "./request.js"
import tabs from "./tabs.js"
import cookie from "./cookie.js"

let path="menu/load";
request(path,{},function(data)
{
  let rows=data.rows;
  let html="";
  //level 1
  let l1s=rows.filter(e=>!e.parent_id).sort((a,b)=>(a.order-b.order));
  for(let item of l1s){
    html+='<li class="header">'+ item.name +'</li>';
    //level 2
    let l2s=rows.filter(e=>e.parent_id==item.id).sort((a,b)=>(a.order-b.order));
    for(let item of l2s){
      html+='\
        <li class="treeview"> \
          <a href="#"><i class="fa '+item.icon+'"></i> <span>'+item.name+'</span> \
            <span class="pull-right-container"> \
                <i class="fa fa-angle-left pull-right"></i> \
              </span> \
          </a> \
          <ul class="treeview-menu"> \
      ';
      //level 3
      let l3s=rows.filter(e=>e.parent_id==item.id).sort((a,b)=>(a.order-b.order));
      for(let item of l3s){
        html+='<li data-pageid='+item.page_id+' data-pagename="'+item.name+'" data-icon="'+item.icon+'"><a href="javascript:void(0);"><i class="fa '+item.icon+'"></i><span>'+item.name+'</span></a></li>';
      }
      //level 2 last part
      html+='\
          </ul> \
        </li>\
      ';
    }
  }
  let tabs_container="tabs_container";
  $("#main-menu").append(html);
  $("#main-menu .treeview-menu>li").click(function() {
    $("#main-menu .treeview-menu>li").removeClass("active");
    $(this).addClass("active");
    let pageid=$(this).data("pageid");
    let pagename=$(this).data("pagename");
    let icon=$(this).data("icon");
    tabs.open(tabs_container,pageid,pagename,icon);
  })
  //URL中的页面ID
  let url_pid=query("pid");
  //首页
  let index_page_id=cookie.getcookie("index_page");
  if(index_page_id){
    tabs.open(tabs_container,index_page_id,'首页','fa-home');
  }
  //URL导航页
  if(url_pid){
    let page_id=url_pid;
    let the_menu=$("li[data-pageid="+page_id+"]").first();
    the_menu.click();
    the_menu.parent().parent().addClass("menu-open");
    the_menu.parent().css("display","block");
  }
});


function query(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}